let grid
window.addEventListener('DOMContentLoaded', async () => {
    const now = new Date();
    now.setHours(now.getHours() + 8);
    const nowISOString = now.toISOString().slice(0, 16); // 转换为 YYYY-MM-DDTHH:MM 格式
    // 获取 24 小时前的时间
    const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const yesterdayISOString = yesterday.toISOString().slice(0, 16); // 转换为 YYYY-MM-DDTHH:MM 格式

    // 初始化 Flatpickr
    flatpickr('#date-range', {
        mode: 'range', // 启用范围选择
        enableTime: true, // 启用时间选择
        dateFormat: 'Y-m-d H:i', // 日期时间格式
        defaultDate: [yesterdayISOString, nowISOString], // 设置初始时间段
    });

    // 提交按钮点击事件
    document.getElementById('query-data-btn').addEventListener('click', async () => {
        const selectedDates = document.getElementById('date-range').value;
        const [startTime, endTime] = selectedDates.split(' to ');
        window.startTime = new Date(startTime);
        window.endTime = new Date(endTime);
        await query_data(new Date(endTime), new Date(startTime), 1);
    });

    document.getElementById('export-data-btn').addEventListener('click', async () => {
        const { open } = window.__TAURI__.dialog;
        const selectedPath = await open({
            directory: true, // 选择文件夹
            multiple: false, // 不允许多选
            title: '选择保存路径' // 窗口标题
        });
        if (selectedPath) {
            let after = new Date(window.endTime)
            let before = new Date(window.startTime)
            let afterString = after.toISOString().slice(0, 16); // 转换为 YYYY-MM-DDTHH:MM 格式
            let beforeString = before.toISOString().slice(0, 16); // 转换为 YYYY-MM-DDTHH:MM 格式
            afterString = afterString.replace(/:/g, '-').replace(/\//g, '-').replace(/T|Z|\./g, '');
            beforeString = beforeString.replace(/:/g, '-').replace(/\//g, '-').replace(/T|Z|\./g, '');
            let baseUrl = Alpine.$data(document.querySelector('[x-data]')).selectedOption
            await invoke('export_xlsx_command', {
                after: after,
                before: before,
                name: baseUrl,
                path: `${selectedPath}/${beforeString}-${afterString}-${baseUrl}.xlsx`
            })
        }
    })

    grid = new gridjs.Grid({
        columns: [],
        data: [],
        width: '100%', // 设置最大宽度
        autoWidth: true, // 自动调整列宽
        style: {
            table: {
                'font-size': '12px', // 设置表格字体大小
            },
            th: {
                'font-size': '14px', // 设置表头字体大小
                'font-weight': 'bold', // 设置表头字体加粗
                'padding': '10px', // 设置单元格内边距
                "text-align": "center", // 设置表头水平居中
            },
            td: {
                'font-size': '12px', // 设置单元格字体大小
                'padding': '10px', // 设置单元格内边距
                "text-align": "center", // 设置单元格水平居中
            },
        },
    }).render(document.getElementById("wrapper"));
})

async function goto_data() {
    if (!window.startTime || !window.endTime) {
        now = new Date();
        const now_timestamp = now.getTime();
        const yesterday_start = new Date(now_timestamp - 24 * 60 * 60 * 1000);
        window.startTime = yesterday_start;
        window.endTime = new Date(now_timestamp);
    }
    await query_data(new Date(window.endTime), new Date(window.startTime), 1)
}

async function query_data(after, before, page) {
    let baseUrl = Alpine.$data(document.querySelector('[x-data]')).selectedOption
    let { data, total } = await invoke('get_data_by_time_range', {
        after: after,
        before: before,
        page: page,
        name: baseUrl
    });
    if (total == 0) {
        grid.updateConfig({
            columns: [],
            data: [],
        }).forceRender(document.getElementById("wrapper"));
    } else {
        let totalPages = Math.ceil(total / 20);
        window.totalPages = totalPages;
        renderPagination(totalPages, page); // 渲染初始分页器

        const columns = Object.keys(data[0]);

        data = data.map((item) => {
            return Object.values(item);
        })

        const columnWidths = calculateColumnWidths(data, columns);
        grid.updateConfig({
            columns: columnWidths,
            data: data,
        }).forceRender(document.getElementById("wrapper"));
    }
    Alpine.$data(document.querySelector('[x-data]')).currentPage = "data";
}
